﻿using Masuit.Tools.Logging;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
using System.Timers;
using Topshelf;

namespace LPLS.DataCollection.Service
{
    public class Program
    {

        public static ServiceProvider ServiceProvider;

        static void Main(string[] args)
        {

            var services = new ServiceCollection();
            LPLS.DBServices.DatabaseConfig.InitDataBaseConfig();
            services.AddSingleton<LPLS.DBEntities.DBContext>(sp => new LPLS.DBEntities.DBContext(LPLS.DBServices.DatabaseConfig.ConfiguredDbContexts));
            // 使用反射自动注册服务
            var serviceTypes = Assembly.Load("LPLS.DBServices").GetTypes()
                .Where(t => t.IsClass && t.GetInterfaces().Any(i => i.Name == "I" + t.Name));
            foreach (var serviceType in serviceTypes)
            {
                var interfaceType = serviceType.GetInterfaces().First(i => i.Name == "I" + serviceType.Name);
                services.AddSingleton(interfaceType, serviceType);
            }
            services.AddSingleton<DataCollectionOP>();
            var serviceProvider = services.BuildServiceProvider();
            ServiceProvider = serviceProvider;
            var greetingService = serviceProvider.GetService<DataCollectionOP>();

            greetingService.Init();
        



            var rc = HostFactory.Run(x =>                         //1.启动程序
            {

                x.Service<TownCrier>(s =>                         //2.设置服务类型
                {
                    s.ConstructUsing(name => new TownCrier());    //3.创建服务实例
                    s.WhenStarted(tc => tc.Start());              //4.启动程序
                    s.WhenStopped(tc => tc.Stop());               //5.停止程序
                });
                x.RunAsLocalSystem();                             //6.本地系统运行

                x.SetDescription("LPLS数据采集服务");         //7.windows服务的描述
                x.SetDisplayName("LPLS数据采集服务");                        //8.windows服务的显示名称
                x.SetServiceName("LPLS.DataCollectionService");                        //9.windows服务的服务名称
            });

            var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());  //11.退出程序
            Environment.ExitCode = exitCode;


            Console.ReadKey();
            Console.WriteLine("Hello, World!");
        }

    }



    public class TownCrier
    {

        public static ServiceProvider ServiceProvider;
        Thread backgroundThread = new Thread(BackgroundWork);

        static System.Timers.Timer timer2 = new System.Timers.Timer();
        static System.Timers.Timer timer1 = new System.Timers.Timer();
        static System.Timers.Timer timer3 = new System.Timers.Timer();

        public TownCrier()
        {
            ServiceProvider = Program.ServiceProvider;

            backgroundThread.IsBackground = true;
            backgroundThread.Start();
        }
        public void Start()
        {

            timer1.Enabled = true;
            timer2.Enabled = true;
            timer3.Enabled = true;


        }
        public void Stop()
        {
            timer1.Enabled = false;
            timer2.Enabled = false;
            timer3.Enabled = false;
        }


      


        private static bool timeer1flag = false;
        private static bool timeer2flag = false;

        public static void BackgroundWork()
        {

            LogManager.Info("开始了");

            Thread t = new Thread(() =>
            {

                ///加载数据
                var service = ServiceProvider.GetService<DataCollectionOP>();
              
                service.LoadData();

            });

            t.IsBackground = true;
            t.Start();

            timer1.Interval = 5000;
            // 设置 Elapsed 事件处理程序
            timer1.Elapsed += OnTime1Event;

            // 设置 Timer 为自动重置
            timer1.AutoReset = true;

            // 启动 Timer
            timer1.Enabled = true;




            timer2.Interval = 1000 * 60;
            // 设置 Elapsed 事件处理程序
            timer2.Elapsed += Timer2_Elapsed; ;

            // 设置 Timer 为自动重置
            timer2.AutoReset = true;

            // 启动 Timer
            timer2.Enabled = true;





            timer3.Interval = 10000;
            // 设置 Elapsed 事件处理程序
            timer3.Elapsed += Timer3_Elapsed; ; ;

            // 设置 Timer 为自动重置
            timer3.AutoReset = true;

            // 启动 Timer
            timer3.Enabled = true;





        }

        private static void Timer3_Elapsed(object? sender, ElapsedEventArgs e)
        {

            try
            {
                var service = ServiceProvider.GetService<DataCollectionOP>();
                service?.DealCollectionData();
            }
            catch (Exception ex)
            {

              LogManager.Error(ex);
            }

         

        }

        private static void Timer2_Elapsed(object? sender, ElapsedEventArgs e)
        {
            if (timeer2flag)
            {
                Console.WriteLine("请稍后。。。");

            }
            else
            {

                try
                {
                    timeer2flag = true;
                    var service = ServiceProvider.GetService<DataCollectionOP>();

                    service.ReLoadData();
                }
                catch (Exception ex)
                {

                    LogManager.Error(ex);
                }
                finally {

                    timeer2flag = false;

                }
            }
        }

        private static void OnTime1Event(object? sender, ElapsedEventArgs e)
        {
            if (!timeer2flag)
            {
                timeer2flag = true;
                try
                {

                    var service = ServiceProvider.GetService<DataCollectionOP>();
                    service.StartOP();


                }
                catch (Exception ex)
                {

                    LogManager.Error(ex);
                }
                finally
                {

                    timeer2flag = false;

                }

            }
            else
            {

                Console.WriteLine("还在获取数据中 请稍后");
                //  LogManager.Info("还在获取数据中 请稍后");

            }
        }


    }














}
